<?php

namespace App\Jobs;

use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Models\Circle\WxCircle;
use App\Wen\Utils\CircleUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImitateCircleJoinStepJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    protected $circle_id = 0;
    protected $need_join = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($circle_id, $need_join)
    {
        //
        $this->circle_id = $circle_id;
        $this->need_join = $need_join;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        global $__MINI_GLOBAL_PAYCODE_9__;
        if(!$__MINI_GLOBAL_PAYCODE_9__){
            return;
        }

        if( $this->need_join <= 0 ){
            return;
        }

        global $__MINI_GLOBAL_REQUEST_ENV__;
        $__MINI_GLOBAL_REQUEST_ENV__ = 'api';

        $circle = WxCircle::find($this->circle_id);
        if(_empty_($circle)){
            return;
        }

        if($circle->circle_state != 1){
            return;
        }

        $uid = UserUtils::get_a_random_robot_uid();
        if($uid > 0){
            $p = CircleUtils::can_i_visit($circle, $uid);
            if($p == 2 || $p == 1){
                return;
            }

            WxCircleRepositores::userFollowCircle($uid, $this->circle_id);

            $circle_user_id = $circle->user_id;
            if($circle_user_id > 0){
                ImitateUserFollowsStepJob::dispatch($circle_user_id, mini_rand(0, 2))->delay(now()->addMinutes(mini_rand(1, 30)));
            }

            ImitateCircleJoinStepJob::dispatch($this->circle_id, ($this->need_join - 1))->delay(now()->addMinutes(mini_rand(6, 30)));
        }
    }
}
